package cn.edu.hqu.javaee.web;


import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.validation.Valid;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.edu.hqu.javaee.domain.Course;
import cn.edu.hqu.javaee.domain.Personal;
import cn.edu.hqu.javaee.domain.Course.Type;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@Scope("singleton")
@RequestMapping("/checkout")
public class PersonalController {
	@ModelAttribute
	public void addCourseToModel(Model model) {
		List<Course> courses = Arrays.asList(
				  new Course("高等数学", "高等数学", Type.BASICS),
				  new Course("离散数学", "离散数学", Type.BASICS),
				  new Course("随机数学", "随机数学", Type.BASICS),
				  new Course("高等代数", "高等代数", Type.BASICS),
				  new Course("c++设计", "c++设计", Type.MAJOR),
				  new Course("java设计", "java设计", Type.MAJOR),
				  new Course("python设计", "python设计", Type.MAJOR),
				  new Course("java web设计", "java web设计", Type.MAJOR),
				  new Course("软件建模与分析", "软件建模与分析", Type.THEORY),
				  new Course("软件工程", "软件工程", Type.THEORY),
				  new Course("软件开发标准与文档", "软件开发标准与文档", Type.THEORY)
				);
		Type[] types = Course.Type.values();
		for (Type type : types) {
		  model.addAttribute(type.toString().toLowerCase(),
		      filterByType(courses, type));
		}
	}
	 private List<Course> filterByType(
		      List<Course> courses, Type type) {
		    return courses.stream().filter(x -> x.getType().equals(type)).collect(Collectors.toList());
		  }
	@GetMapping("/personal")//http://localhost:8080/checkout/personal
		public String personal(Model model) {
			model.addAttribute("personal",new Personal());
			 System.out.println("Model"+model);
			return "personal";//personal---templates里面的personal.html
		}
	 @PostMapping
	 public String processPersonal(@Valid @ModelAttribute("personal") Personal personal,Errors errors,ModelMap model) {
		 if(errors.hasErrors()) {
			 return "personal";
		 }
	   System.out.println("post"+personal);	   
	   System.out.println("postModel"+model.get("personal"));
	   System.out.println("Model--p"+model);
	   log.info("personal submitted: " + personal);
	   return "choose";
	 }		
}
